package IPADistribution.Servlets;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

@WebServlet(name = "Download")
public class Download extends HttpServlet {
    private String param_filePath = "filePath";
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置服务端编码格式
        response.setCharacterEncoding("UTF-8");

        String filePath = request.getParameter(param_filePath);
        if (filePath == null) {
            //设置客户端解码格式
            response.setContentType("text/html; charset=UTF-8");
            response.getWriter().write("param invalid!");
            return;
        }

        String realPath = request.getServletContext().getRealPath("WEB-INF"+ File.separator+filePath);
        File file = new File(realPath);
        if (!file.exists()){
            //设置客户端解码格式
            response.setContentType("text/html; charset=UTF-8");
            response.getWriter().write("文件不存在");
            return;
        }

        //设置响应头
        response.setHeader("content-disposition", "attachment;filename=" +
                URLEncoder.encode(FilenameUtils.getName(realPath), "UTF-8"));

        FileInputStream fileInputStream = new FileInputStream(file);
        OutputStream outputStream = response.getOutputStream();

        //将文件写入输出流
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len=fileInputStream.read(buffer))>0){
            outputStream.write(buffer, 0, len);
        }
        fileInputStream.close();
        outputStream.close();
    }
}
